import {
  Controller,
  Post,
  Get,
  Put,
  Delete,
  Body,
  Param,
  UseGuards,
  Req,
  UploadedFile,
  UseInterceptors,
} from '@nestjs/common';
import { UserService } from './user.service';
import {
  CreateUserDto,
  UpdateUserDto,
  LoginUserDto,
  UserResponseDto,
} from './user.dto';
import { AuthGuard } from '@nestjs/passport';
import { FileInterceptor } from '@nestjs/platform-express';
import { imageMulterConfig } from '../common/config/multer.config';
import {
  ApiTags,
  ApiOperation,
  ApiResponse,
  ApiParam,
  ApiConsumes,
  ApiBody,
} from '@nestjs/swagger';

@ApiTags('用户')
@Controller('users')
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Post('register')
  async register(
    @Body() createUserDto: CreateUserDto,
  ): Promise<UserResponseDto> {
    console.log(createUserDto);
    return this.userService.createUser(createUserDto);
  }

  @Post('login')
  async login(
    @Body() loginUserDto: LoginUserDto,
  ): Promise<{ access_token: string }> {
    return this.userService.login(loginUserDto);
  }

  @UseGuards(AuthGuard('jwt'))
  @Get()
  async findAll(): Promise<UserResponseDto[]> {
    return this.userService.findAllUsers();
  }

  // @UseGuards(AuthGuard('jwt'))
  // @Get(':id')
  // async findOne(@Param('id') id: number): Promise<UserResponseDto> {
  //   return this.userService.findUserById(id);
  // }

  @UseGuards(AuthGuard('jwt'))
  @Put(':id')
  async update(
    @Param('id') id: number,
    @Body() updateUserDto: UpdateUserDto,
  ): Promise<UserResponseDto> {
    return this.userService.updateUser(id, updateUserDto);
  }

  @UseGuards(AuthGuard('jwt'))
  @Delete(':id')
  async delete(@Param('id') id: number): Promise<void> {
    return this.userService.deleteUser(id);
  }

  // 获取当前登录用户信息
  @UseGuards(AuthGuard('jwt'))
  @Get('me')
  async getCurrentUser(
    @Req() req: { user: { id: number } },
  ): Promise<UserResponseDto> {
    return this.userService.getCurrentUser(req.user.id);
  }

  // 退出登录
  @UseGuards(AuthGuard('jwt'))
  @Post('logout')
  async logout(): Promise<{ message: string }> {
    await this.userService.logout();
    return { message: '退出登录成功' };
  }

  @ApiOperation({ summary: '上传用户头像' })
  @ApiResponse({ status: 200, description: '头像上传成功' })
  @ApiResponse({ status: 404, description: '用户不存在' })
  @ApiResponse({ status: 400, description: '文件上传失败' })
  @ApiParam({ name: 'id', description: '用户ID' })
  @ApiConsumes('multipart/form-data')
  @ApiBody({
    schema: {
      type: 'object',
      properties: {
        file: {
          type: 'string',
          format: 'binary',
        },
      },
    },
  })
  @UseGuards(AuthGuard('jwt'))
  @Post(':id/avatar')
  @UseInterceptors(FileInterceptor('file', imageMulterConfig))
  async uploadUserAvatar(
    @Param('id') id: number,
    @UploadedFile() file: Express.Multer.File,
  ): Promise<{ avatarUrl: string }> {
    return this.userService.uploadUserAvatar(id, file);
  }
}
